import { engine } from '@/api';
import ProTable from '@/components/proTable';
import modal from '@/utils/modal';
import { useModel } from '@umijs/max';
import { Space, message, type TableProps } from 'antd';
import dayjs from 'dayjs';
import { useEffect, useMemo, useRef, useState } from 'react';
import EngineForm from './components/engineForm';
import EngineInfo from './components/engineInfo';
import { DataType } from './constant';

const HomePage: React.FC = () => {
  const [loading, setLoading] = useState(false);
  const [data, setData] = useState<DataType[]>([]);
  const modalInstance = useRef<{ destroy: () => void } | null>(null);
  const { userId } = useModel('global');

  function getEngineList() {
    setLoading(true);
    engine.getEngineList(userId).then((res: any) => {
      let newData = res.data?.map((item: any) => {
        let {
          name,
          spec: { cpus, memory, enableGpu },
          image,
          endpoint,
        } = item;
        delete item.spec;
        delete item.name;
        delete item.image;
        delete item.endpoint;

        return {
          engineName: name,
          cpus,
          memory,
          enableGpu,
          engineImage: image,
          engineLink: endpoint,
          ...item,
        };
      });
      setData(newData || []);
      setLoading(false);
    });
  }

  useEffect(() => {
    getEngineList();
  }, [userId]);

  function releaseEngine(record: DataType) {
    return modal({
      title: `确认要删除渲染引擎“${record.engineName}”吗？`,
      content: '该操作无法进行复原，请谨慎操作。',
      type: 'confirm',
      classname: 'dangerModal',
      okText: '删除',
      callback: () => {
        engine
          .releaseEngine(userId, record.engineId)
          .then((res: any) => {
            if (res.code === 200) {
              message.success('删除成功');
              return getEngineList();
            } else {
              throw new Error(res?.errmsg || '删除失败');
            }
          })
          .catch((err) => {
            message.error(err?.errmsg || '删除失败');
          });
      },
    });
  }

  function closeCreateEngine() {
    if (!modalInstance) return;
    modalInstance.current?.destroy();
  }

  function createEngine() {
    const instance = modal({
      title: '申请渲染引擎',
      content: (
        <EngineForm
          destoryModal={closeCreateEngine}
          callback={getEngineList}
          userId={userId}
        />
      ),
      footer: null,
      width: 520,
      type: 'info',
    });
    modalInstance.current = instance;
  }

  function getEngineInfo(record: DataType) {
    let engineData = {
      engineId: record.engineId,
      engineName: record.engineName,
      cpus: record.cpus,
      memory: record.memory,
      enableGpu: record.enableGpu ? '是' : '否',
      engineImage: record.engineImage,
      engineLink: record.engineLink || '',
    };

    modal({
      title: '查看渲染引擎',
      content: <EngineInfo data={engineData} />,
      width: 520,
      type: 'info',
    });
  }

  const columns: TableProps<DataType>['columns'] = useMemo(
    () => [
      {
        title: '引擎ID',
        dataIndex: 'engineId',
        key: 'engineId',
      },
      {
        title: '引擎名称',
        dataIndex: 'engineName',
        key: 'engineName',
      },
      {
        title: 'CPU（核）',
        dataIndex: 'cpus',
        key: 'cpus',
      },
      {
        title: '内存（GB）',
        key: 'memory',
        dataIndex: 'memory',
      },
      {
        title: '是否启用GPU',
        key: 'enableGpu',
        dataIndex: 'enableGpu',
        render: (text) => (text ? '是' : '否'),
      },
      {
        title: '创建时间',
        key: 'createTime',
        dataIndex: 'createTime',
        render: (text) => dayjs(text).format('YYYY-MM-DD HH:mm:ss'),
      },
      {
        title: '操作',
        key: 'action',
        render: (_, record) => {
          return (
            <Space size="middle">
              <a onClick={() => getEngineInfo(record)}>查看</a>
              <a className={'dangerBtn'} onClick={() => releaseEngine(record)}>
                删除
              </a>
            </Space>
          );
        },
      },
    ],
    [userId],
  );

  return (
    <ProTable
      title="渲染引擎管理"
      buttonText="申请引擎"
      buttonAction={createEngine}
      columns={columns}
      loading={loading}
      data={data}
    />
  );
};

export default HomePage;
